package team.unstudio.unknownrpg_base.attribute.quality;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;

import team.unstudio.udpl.config.AutoCharsetYamlConfiguration;

public class YamlQualityFile implements QualityFile {
	
	private YamlConfiguration yaml;
	
	private File file;
	
	private final static String ATTRIBUTE = "Attribute.";
	
	private final static String QUALITY = "Quality.";
	
	private Set<String> qualities = new HashSet<>();
	
	public YamlQualityFile(File file) {
		this.file=file;
		reload();
	}

	@Override
	public int getAttributeScore(String attributeKeyName) {
		if(!yaml.contains(ATTRIBUTE+attributeKeyName))return 0;
		return yaml.getInt(ATTRIBUTE+attributeKeyName);
	}

	@Override
	public String[] getQualities() {
		if(qualities.isEmpty())loadQualityList();
		return this.qualities.toArray(new String[0]);
	}
	
	private void loadQualityList() {
		for(String key : yaml.getKeys(true)) {
			if(!key.startsWith(QUALITY))continue;
			String quality = key.split("[/.]")[1];
			this.qualities.add(quality);
		}
	}

	@Override
	public int getQualityScore(String quality) {
		if(!yaml.contains(QUALITY+quality))return 0;
		return yaml.getInt(QUALITY+quality);
	}
	
	public void reload() {
		if(!file.exists())Bukkit.getLogger().info("cannot load file:"+file.getName()+" because file not exists");
		this.yaml=AutoCharsetYamlConfiguration.loadConfiguration(file);
		this.qualities.clear();
	}

}
